package com.sinoglobal.ningxia.activity.player;

import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.orhanobut.logger.Logger;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.beans.LiveHomeBean;
import com.sinoglobal.ningxia.frame.ShareAbstractActivity;
import com.sinoglobal.ningxia.utils.UrlUtils;

/**
 * Created by XINDZ on 2017/2/24.
 * 功能:记者直播的Activity
 */
@SuppressLint("SetJavaScriptEnabled")
public class ReporterLiveActivity extends ShareAbstractActivity {

    private WebView video;
    private LiveHomeBean.ListBean dataBean;
    private View xCustomView;
    private String liveTitle = "";
    private String liveName = "";
    private WebChromeClient.CustomViewCallback xCustomViewCallback;
    private FrameLayout videoFullView;
    private ReporterLiveActivity.MyWebChromeClient chromeClient;
    /**
     * 链接中取到的title
     */
    private String navTitle = "";
    /**
     * 默认传过来的title
     */
    private String def_navTitle = "";
    private String shareImg = "";
    private String shareContent = "";
    private String def_shareContent = "";
    private String shareUrl = "";
    private String def_shareUrl = "http://3g.nxtv.cn/fm/?chn=1061";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reporterlive);
        openChenJInShi();
        dataBean = (LiveHomeBean.ListBean) getIntent().getSerializableExtra(LiveHomeBean.class.getCanonicalName());
        if (dataBean != null) {
            liveTitle = dataBean.getTitle();
            liveName = dataBean.getName();
        }
        if (liveTitle != null && !liveTitle.equals("")) {
            titleView.setText(liveTitle);
            //设置默认title
            def_navTitle = liveTitle;
            //默认分享的内容为标题
            def_shareContent = liveTitle;
            def_shareUrl = "http://3g.nxtv.cn/reporter/?phone=" + liveName;
            templateButtonRight.setBackgroundResource(R.drawable.sharelogo);
//            templateButtonRight.setText("分享");
//            templateButtonRight.setTextColor(getResources().getColor(R.color.white));
            sharePop(def_navTitle, null, def_shareUrl);
        }

        video = (WebView) findViewById(R.id.wv_reporterlive);
        videoFullView = (FrameLayout) findViewById(R.id.video_follView);
        WebSettings settings = video.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setSaveFormData(true);
        settings.setLoadWithOverviewMode(true);
        settings.setBuiltInZoomControls(false);
        settings.setSupportZoom(false);
        settings.setDisplayZoomControls(false);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        chromeClient = new MyWebChromeClient();
        video.setWebChromeClient(chromeClient);
//        video.loadUrl("http://3g.nxtv.cn/fm/?chn=1061");//测试全屏
        video.loadUrl("http://3g.nxtv.cn/reporter/?phone=" + liveName);
        video.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                String urlDecoder = UrlUtils.getUrlDecoder(url);
                if (urlDecoder != null) {
                    Logger.e("URL:" + urlDecoder);
                    navTitle = UrlUtils.getValueByName(url, "navtitle");
                    navTitle = UrlUtils.getUrlDecoder(navTitle);
                    titleView.setText(navTitle.equals("") ? def_navTitle : navTitle);

                    shareContent = UrlUtils.getValueByName(url, "share_text");
                    shareContent = UrlUtils.getUrlDecoder(shareContent);

                    shareUrl = UrlUtils.getValueByName(url, "share_url");
                    shareUrl = UrlUtils.getUrlDecoder(shareUrl);

                    shareImg = UrlUtils.getValueByName(url, "share_img");
                    shareImg = UrlUtils.getUrlDecoder(shareImg);
                    Logger.e("share_img:" + shareImg+"**shareUrl:");
                    sharePop(shareContent.equals("") ? def_shareContent : shareContent,
                            shareImg.equals("") ? null : shareImg,
                            shareUrl.equals("") ? def_shareUrl : shareUrl);
                }
                view.loadUrl(url);
                return true;
            }
        });
    }

    /**
     * 分享
     *
     * @param content  内容
     * @param imgPath  图片
     * @param shareUrl 分享链接
     */
    private void sharePop(final String content, final String imgPath, final String shareUrl) {
        templateButtonRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopwindow(true, content, imgPath, shareUrl);
            }
        });
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            video.setVisibility(View.INVISIBLE);
            if (xCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }
            videoFullView.addView(view);
            xCustomView = view;
            xCustomViewCallback = callback;
            videoFullView.setVisibility(View.VISIBLE);
            titleRelativeLayout.setVisibility(View.GONE);
        }

        @Override
        public void onHideCustomView() {
            if (xCustomView == null) {
                return;
            }
            titleRelativeLayout.setVisibility(View.VISIBLE);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            xCustomView.setVisibility(View.GONE);
            videoFullView.removeView(xCustomView);
            xCustomView = null;
            videoFullView.setVisibility(View.GONE);
            xCustomViewCallback.onCustomViewHidden();
            video.setVisibility(View.VISIBLE);
            video.reload();
        }

    }

    public boolean inCustomView() {
        return xCustomView != null;
    }

    public void hideCustomView() {
        chromeClient.onHideCustomView();

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @Override
    protected void onResume() {
        super.onResume();
        video.onResume();
        video.resumeTimers();
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        video.onPause();
        video.pauseTimers();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (video.canGoBack()) {
                video.goBack();
                return true;
            } else if (inCustomView()) {
                hideCustomView();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//		if (dialog.isShowing()) {
//			dialog.dismiss();
//		}
        videoFullView.removeAllViews();
        video.setVisibility(View.GONE);
        video.stopLoading();
        video.setWebChromeClient(null);
        video.setWebViewClient(null);
        video.destroy();
    }

    @Override
    public void finish() {
        ViewGroup decorView = (ViewGroup) getWindow().getDecorView();
        decorView.removeAllViews();
        super.finish();
    }
}
